const fs = require('fs');
const path = require('path');
const mammoth = require('mammoth');
const sharp = require('sharp');

// 转换DOCX到HTML的函数
exports.convertDocxToHtml = async function(filePath, options = {}) {
  // 自定义样式映射
  const styleMap = [
    "p[style-name='Title'] => h1",
    "p[style-name='Heading 1'] => h1",
    "p[style-name='Heading 2'] => h2",
    "p[style-name='Heading 3'] => h3",
    "p[style-name='Heading 4'] => h4",
    "p[style-name='Heading 5'] => h5",
    "p[style-name='Heading 6'] => h6"
  ];

  // 默认选项
  const defaultOptions = {
    quality: 0.01 // 默认质量参数（0-1之间）
  };

  // 合并选项
  const mergedOptions = { ...defaultOptions, ...options };

  // 转换DOCX为HTML，将图片转为Base64内嵌
  const result = await mammoth.convertToHtml({
    path: filePath
  }, {
    styleMap: styleMap,
    convertImage: mammoth.images.imgElement(async function (image) {
      const imageBuffer = await image.read();
      // 图片压缩配置
      const compressConfig = {
        maxWidth: 930,    // 最大宽度，超过将按比例缩小
        quality: mergedOptions.quality,     // 质量参数（0-1之间）
        withMetadata: false // 移除元数据以减小大小
      };

      // 使用sharp压缩图片
      let compressedBuffer = imageBuffer;
      const originalSize = imageBuffer.length;

      // 只压缩较大的图片（大于10KB）
      if (originalSize > 10 * 1024) {
        try {
          // 根据图片类型选择合适的压缩方式
          if (image.contentType === 'image/png') {
            // PNG使用0-100之间的quality值
            compressedBuffer = await sharp(imageBuffer)
              .resize(compressConfig.maxWidth)
              .png({ quality: Math.round(compressConfig.quality * 100), force: true })
              .toBuffer();
          } else if (image.contentType === 'image/jpeg' || image.contentType === 'image/jpg') {
            // JPEG使用0-100之间的quality值
            compressedBuffer = await sharp(imageBuffer)
              .resize(compressConfig.maxWidth)
              .jpeg({ quality: Math.round(compressConfig.quality * 100), progressive: true })
              .toBuffer();
          } else {
            // 对于其他类型，只调整大小
            compressedBuffer = await sharp(imageBuffer)
              .resize(compressConfig.maxWidth)
              .toBuffer();
          }
        } catch (error) {
          console.error('图片压缩失败，使用原图:', error.message);
        }
      }

      // 将压缩后的图片转为Base64字符串
      const base64String = compressedBuffer.toString('base64');
      const contentType = image.contentType;
      const base64DataUri = `data:${contentType};base64,${base64String}`;

      // 返回带有Base64数据URI的图片元素
      return { src: base64DataUri };
    })
  });

  const htmlContent = result.value;
  const messages = result.messages;

  // 生成完整的HTML文件内容
  const fullHtml = `<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>DOCX转换结果</title>
    <style>
        /* 基础样式 */
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Microsoft YaHei', sans-serif;
            line-height: 1.6;
            color: #333;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .content {
            background-color: white;
            padding: 40px;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        /* 标题样式 */
        h1, h2, h3, h4, h5, h6 {
            color: #2c3e50;
            margin-top: 1.5em;
            margin-bottom: 0.8em;
        }
        h1 {
            font-size: 2.5em;
            border-bottom: 3px solid #3498db;
            padding-bottom: 0.3em;
        }
        h2 {
            font-size: 2em;
            border-bottom: 2px solid #3498db;
            padding-bottom: 0.3em;
        }
        /* 段落样式 */
        p {
            margin-bottom: 1em;
            text-align: justify;
        }
        /* 图片样式 */
        img {
            max-width: 100%;
            height: auto;
            display: block;
            margin: 20px auto;
            border-radius: 4px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        /* 表格样式 */
        table {
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
        }
        th, td {
            padding: 12px;
            text-align: left;
            border: 1px solid #ddd;
        }
        th {
            background-color: #f2f2f2;
            font-weight: bold;
        }
        tr:nth-child(even) {
            background-color: #f9f9f9;
        }
        /* 响应式设计 */
        @media (max-width: 768px) {
            body {
                padding: 10px;
            }
            .content {
                padding: 20px;
            }
            h1 {
                font-size: 2em;
            }
            h2 {
                font-size: 1.5em;
            }
        }
    </style>
</head>
<body>
    <div class="content">
        ${htmlContent}
    </div>
</body>
</html>`;

  // 按一级标题分割内容
  const splitContentByH1 = (content) => {
    const h1Regex = /<h1[^>]*>(.*?)<\/h1>/g;
    const sections = [];
    let currentSection = null;
    let lastIndex = 0;
    let match;

    while ((match = h1Regex.exec(content)) !== null) {
      const h1Content = match[1];
      const h1Start = match.index;
      const h1End = h1Regex.lastIndex;

      if (currentSection && lastIndex < h1Start) {
        currentSection.content = content.substring(lastIndex, h1Start).trim();
        sections.push(currentSection);
      }

      currentSection = {
        title: h1Content,
        content: '',
        startIndex: h1Start
      };

      lastIndex = h1Start;
    }

    if (currentSection && lastIndex < content.length) {
      currentSection.content = content.substring(lastIndex).trim();
      sections.push(currentSection);
    }

    return sections;
  };

  // 清理文件名，移除特殊字符
  const sanitizeFilename = (filename) => {
    return filename
      .replace(/[\\/:*?"<>|]/g, '_')
      .replace(/\s+/g, '_')
      .substring(0, 100);
  };

  const sections = splitContentByH1(htmlContent);

  return {
    fullHtml: fullHtml,
    contentOnly: htmlContent,
    sections: sections,
    messages: messages
  };
};

// 获取文件名（不包含扩展名）
exports.getFileNameWithoutExt = function(filePath) {
  return path.basename(filePath, path.extname(filePath));
};

// 清理文件名
exports.sanitizeFilename = function(filename) {
  return filename
    .replace(/[\\/:*?"<>|]/g, '_')
    .replace(/\s+/g, '_')
    .substring(0, 100);
};